import Layout from '@/Layout/index.vue'
import { useUserStore } from '@/store/user'
import { RouteRecordRaw } from 'vue-router'
import router from '.'

function loadView (viewName: string): () => Promise<any> {
  return () => import(`@/views/${viewName}`)
}

function buildMenuList (menuList: RouteRecordRaw[]): RouteRecordRaw[] {
  return menuList.map((item) => {
    const isChildren = item.children && item.children.length > 0
    return {
      ...item,
      component: isChildren ? Layout : loadView(item.component as unknown as string),
      children: isChildren ? buildMenuList(item.children || []) : []
    } as RouteRecordRaw
  })
}

export async function registeredUserRoute () {
  const userStore = useUserStore()
  const menuList = await userStore.getUserInfo()
  buildMenuList(menuList).forEach((m) => {
    router.addRoute(m)
  })
}
